<template>
  <div>
    <el-dialog v-if="enable" :visible.sync="enable" :title="editorTitle" width="90%" >
      <div class="file-text-editor">
        <codemirror v-model="content" :options="editorOptions"></codemirror>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button type="primary" :disabled="content==contentOriginal" @click="actionSave">保存</el-button>
      </span>
    </el-dialog>
  </div>
</template>
<script>
import { codemirror } from 'vue-codemirror'
import "codemirror/theme/ambiance.css";
require("codemirror/mode/javascript/javascript");
require("codemirror/mode/shell/shell");
export default {
    name : 'FileTextEditor',
    components : {
        codemirror,
    },
    data() {
        return {
            sftp : null,
            enable : false,
            filepath : null,
            contentOriginal : '',
            content : '',
            editorOptions : {
                mode:'shell',
                theme: 'ambiance',
                readOnly:false,
                lineNumbers:true,
                lineWrapping:true,
                autofocus:true,
            },
        };
    },
    computed : {
        editorTitle() {
            let title = ['文件编辑：'];
            title.push(this.filepath);
            if ( this.content != this.contentOriginal ) {
                title.push('*');
            }
            return title.join(' ');
        },
    },
    methods : {
        /**
         * 打开文件
         * @param {string} filepath
         */
        async open( filepath ) {
            let server = this.$store.getters.serverCurrent;
            this.contentOriginal = await server.fileGetContent(filepath);
            this.content = this.contentOriginal;
            this.filepath = filepath;

            let extPos = filepath.lastIndexOf(".");
            if ( -1 == extPos ) {
                this.editorOptions.mode = 'shell';
            } else {
                let extname = filepath.substr(extPos+1);
                this.setupEditorMode(extname);
            }
            this.enable = true;
        },

        // 设置编辑器模式
        setupEditorMode( extname ) {
            let extmap = {
                'js' : 'javascript',
            };
            if ( undefined != extmap[extname] ) {
                this.editorOptions.mode = extmap[extname];
            } else {
                this.editorOptions.mode = 'shell';
            }
        },

        // 保存文件
        async actionSave() {
            let server = this.$store.getters.serverCurrent;
            await server.filePutContent(this.filepath, this.content);
            this.enable = false;
        }
    },
}
</script>
<style>
.file-text-editor .CodeMirror {height: 500px !important;}
</style>